﻿using System;
using Newtonsoft.Json;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;

namespace carApp.Libs
{
    public class wx
    {
        public static string appid = "wxdf57d44e60b54d2f";
        public static string appSecret = "eda24592d2e7b8afaceab0235e445e47";
        public static string getToken()
        {
            //生成tokcen
            string accessToken = "";
            bool ReGet = true;
            string spath = "";
            string tockenpath = spath + "token.txt";
            string exptimepath = spath + "expie.txt";
            if (FileHelper.IsExistFile(tockenpath))
            {
                string _exptime = FileHelper.ReadTxt(exptimepath);

                if (_exptime != "")
                {
                    if (Utils.StrDateDiffSeconds(_exptime, 0) < 7198)
                    {
                        ReGet = false;
                        accessToken = FileHelper.ReadTxt(tockenpath);
                    }
                }
            }
            if (ReGet)
            {
                accessToken = GetAccessToken();
                FileHelper.WriteText(tockenpath, accessToken,Encoding.UTF8);
                FileHelper.WriteText(exptimepath, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),Encoding.UTF8);
            }
            return accessToken;
        }
        public static string GetAccessToken()
        {
            string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", appid, appSecret);
            var wc = new WebClient();
            var strReturn = wc.DownloadString(tokenUrl);
            //DAL.Logs.WriteTxt("token.txt", strReturn);
            JObject TokenJO = (JObject)JsonConvert.DeserializeObject(strReturn);
            strReturn = TokenJO["access_token"].ToString();
            return strReturn;
        }
    }
}
